<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Bookmarks_model extends CI_Model{
    
    public function __construct() {
        parent::__construct();
    }

    /**!!!
     * Возвращает массив всех закладок текущего пользователя вместе с папками
     * @return array
     */
    public function get_bookmarks(){
        $user_id = $this->session->userdata('uid');
        $query = $this->db->query("SELECT bookmarks.*, resolv.r_path, resolv.r_hash FROM bookmarks left join ".$this->config->item('resolv_table')." resolv on bookmarks.type_id = resolv.r_id WHERE user_id = ? ORDER BY Decode(type_id,null,0,1) asc, type, r_path ASC",array($user_id));
        
        $bookmarks = array();
        foreach ($query->result_array() as $row){

            if($row['TYPE_ID'] == NULL){
                $name = $row['TYPE'];
                $is_folder = TRUE;
            }else{
                $name = $row['R_PATH'];
                $is_folder = FALSE;
            }
            $bookmarks[$row['ID']] = array('id'       => $row['ID'],
                                           'name'     => $name,
                                           'type_id'  => $row['TYPE_ID'],
                                           'is_folder'=> $is_folder,
                                           'hash'     => $row['R_HASH'],
                                           'parent_id'=> $row['PARENT_ID']);
        }
        return $bookmarks;
    }
    
    /**!!!
     * Возвращает массив объектов всех закладок текущего пользователя без папок
     * @param $hash Hash root node (optional)
     * @return array BinaryNode
     */
    public function get_list_bookmarks($hash=NULL){
        $user_id = $this->session->userdata('uid');
        if(empty($hash)){
            $query = $this->db->query("SELECT bookmarks.*, resolv.* FROM bookmarks inner join ".$this->config->item('resolv_table')." resolv on bookmarks.type_id = resolv.r_id WHERE user_id = ? ORDER BY r_path ASC",array($user_id));
        }else{
            $query = $this->db->query("SELECT bookmarks.*, resolv.* FROM bookmarks inner join ".$this->config->item('resolv_table')." resolv on bookmarks.type_id = resolv.r_id WHERE user_id = ? AND R_PATH LIKE ? ORDER BY r_path ASC",array($user_id,'%'.$hash.'%'));
        }
        $bookmarks = array();
        foreach ($query->result_array() as $row){
            $node_obj = new BinaryNode();
            $bookmarks[$row['R_HASH']] = $node_obj->set_by_rowdb($row);
        }
        return $bookmarks;
    }
    
    /**!!!
     * 
     * @param string $node_hash
     * @param int $pid
     * @return bool TRUE on success or FALSE on failure.
     */
    public function add_bookmark_to_profile($node_hash,$pid=0){
        return $this->db->query("INSERT INTO bookmarks (user_id,type,type_id,parent_id) VALUES (?,'bookmark',(SELECT r_id from ".$this->config->item('resolv_table')." where r_hash = ?),?)",array((int)$this->session->userdata('uid'),$node_hash,(int)$pid));
    }

    /**!!!
     * 
     * @param int $bookmark_id
     * @return bool TRUE on success or FALSE on failure.
     */
    public function remove_bookmark_from_profile($bookmark_id){
        return $this->db->query("DELETE FROM bookmarks WHERE id = ? AND user_id = ?",array($bookmark_id, $this->session->userdata('uid')));
    }

    /**!!!
     * 
     * @param int $bookmark_id
     * @param int $parent_id
     * @return bool TRUE on success or FALSE on failure.
     */
    public function change_parent($bookmark_id,$parent_id){
        return $this->db->query("UPDATE bookmarks SET parent_id = ? WHERE id = ? ",array($parent_id,$bookmark_id));
    }
    
    /**!!!
     * 
     * @param int $bookmark_id
     * @param int $parent_id
     * @return bool TRUE on success or FALSE on failure.
     */
    public function copy_bookmark($bookmark_id,$parent_id){
        return $this->db->query('insert into bookmarks (user_id,"TYPE",type_id,parent_id) (select user_id, "TYPE", type_id, ? from bookmarks where id = ?)',array($parent_id,$bookmark_id));
    }

    /**!!!
     * Insert or Update Folder in bookmarks
     * @param string $folder_name
     * @param int $folder_id
     * @return bool TRUE on success or FALSE on failure.
     */
    public function modify_folder($folder_name,$folder_id = null){
        $folder_name = replace_quotes(str_replace(" ","_",urldecode(trim($folder_name))));
        if($folder_id == null){
            $res = $this->db->query("INSERT INTO bookmarks (user_id,type) VALUES (?,?)",array($this->session->userdata('uid'),$folder_name));
        }else{
            $res = $this->db->query("UPDATE bookmarks SET type = ? WHERE id = ? AND user_id = ? ",array($folder_name,$folder_id,$this->session->userdata('uid')));
        }
        return $res;
    }
    
    /**!!!
     * Возвращает список элементов закладки без папок
     * @param string $node Node ID or Node HASH
     * @param boolean $is_folder
     * @return array BinaryNode
     */
    public function get_list_charts($node,$is_folder){
        $res = array();
        if($is_folder){
            $query = $this->db->query("select b.*, r.*, level from bookmarks b left join resolv_list r on b.type_id = r.r_id where b.user_id = ? START WITH b.id = ? connect by prior b.id = b.parent_id order by level, R_PATH", array($this->session->userdata('uid'),$node));
            foreach ($query->result_array() as $row) {
                if($row['TYPE_ID'] !== NULL){
                    $node_obj = new BinaryNode($row);
                    $res[$node_obj->get_hash()] = $node_obj;
                }
            }
        }else{
            $node_obj = $this->node_model->get_node($node);
            $res[$node_obj->get_hash()] = $node_obj;
        }
        return $res;
    }
    
    /**!!!
     * Копирование закладок другому пользователю
     * @param int $bookmark_id
     * @param string $to_user
     * @return boolean
     */
    public function share_bookmarks($bookmark_id, $to_user){
        $query = $this->db->query("Select * from users where user_name = ?", array($to_user));
        if ($query->num_rows() > 0){
            $row = $query->row_array();
            $proc = $this->db->query("call COPY_BOOKMARKS( ? , ? , ? )",array($bookmark_id,$row['ID'],$this->session->userdata('login')));
            return $proc == FALSE?FALSE:TRUE;
        }else{
            return FALSE;
        }
    }
    
    
    /******************** new func version 2.0 *********************************************************/
//            $this->firephp->log("message");
    
    public function get_tree_bookmarks() {
        return $this->make_tree_bookmarks($this->get_bookmarks(),$this->user_profiles->get_u_bookmarks());
    }
    
    private function make_tree_bookmarks($bookmarks, $user_bookmarks, $pid = '0'){
        $displ = array_key_exists($pid, $user_bookmarks) || $pid == 0 ? "block" : "none";
        $tree = '<ul style="display:' . $displ . ';">';
        foreach ($bookmarks as $bookmark) { // $key => $val
            if ($bookmark['parent_id'] == $pid) {
                if ($bookmark['is_folder']) {
                    if (array_key_exists($bookmark['id'], $user_bookmarks)) {
                        $imgbkmk = "/images/open-bookmark.gif";
                    } else {
                        $imgbkmk = "/images/bookmark.gif";
                    }
                    $tree .= sprintf('<li class="bmdir" id="%1$s"><img src="%3$s" class="folder hand" align="bottom" title="Развернуть/Свернуть" alt="Развернуть/Свернуть">'.
                            '<a href="/chart/bookmark/fld/%1$s" id="a%1$s" name="abkmk" title="%2$s">%2$s</a>'.
                            /*'<em name="eme"><a href="#" class="hand" name="renbk%1$s">Переименовать</a><br><a href="#" class="hand" name="movbk%1$s">В корень</a><br>'.
                            '<a href="#" class="hand" name="shabk%1$s">Поделиться</a><br><a href="#" class="hand" name="delbk%1$s">Удалить</a></em>'.*/
                            "\n",$bookmark['id'],$bookmark['name'],$imgbkmk);
                    $tree .= $this->make_tree_bookmarks($bookmarks, $user_bookmarks, $bookmark['id']);
                    $tree .= '</li>';
                } else {
                    $tree .= sprintf('<li class="bmfile" id="%1$s">'.
                            '<img src="/images/star-small-half.gif" class="fav hand" align="bottom" title="Убрать из закладок" alt="Убрать из закладок">'.
                            '<a href="/chart/bookmark/%2$s" title="%3$s">%3$s</a></li>',
                            $bookmark['id'],$bookmark['hash'],$this->parse_title($bookmark['name']));
                    /*$tree .= '<li class="bmfile">';
                    $tree .= '<img src="/images/star-small-half.gif" id="bkmrk' . $bookmark['id'] . '" class="fav hand" align="bottom" title="Удалить" alt="Удалить">';
                    $tree .= '<a href="/chart/bookmark/' . $bookmark['hash'] . '" title="">' . $this->parse_title($bookmark['name']) . '</a>';
                    $tree .= '</li>';*/
                }
            }
        }
        $tree .= "</ul>";
        return $tree;
    }
    
    private function parse_title($title){
        $patterns = $this->config->item('title_patterns');
        $replaces = $this->config->item('title_replaces');
        
        /*if (false === strpos($title, $this->config->item("path_dir_rrd"))) {
            $str = preg_replace($patterns, $replaces, $title);
        } else { //*/
            $str = preg_replace($patterns, $replaces, substr($title, strlen($this->config->item("path_dir_rrd")) + 1));
        //}
        return strlen($str) > 0 ? $str : $this->config->item('empty_string');
    }
    
    

}
